//
//  MTKRawCmdVC.swift
//  SDKDebuggingDemo
//
//  Created by 秦晟哲 on 2019/8/19.
//  Copyright © 2019 QinszQSZ. All rights reserved.
//

import UIKit
import KCTBluetoothSDK

class KCTMTKTaskSendVC: UIViewController, UITableViewDataSource, UITableViewDelegate, KCTMTKShellManagerDelegate {
    func mtkShellManager(scanPeripheral: CBPeripheral) {
        
    }
    
            
    //MARK: - Property -
    private let headerName = ["SET 设置 杂项",
                              "GET 获取 杂项",
                              "Device 设备",
                              "Step 步数",
                              "Sleep 睡眠",
                              "Sport 运动",
                              "HeartRate 心率",
                              "ECG 心电",
                              "BloodPressure 血压",
                              "BloodOxygen 血氧",
                              "Dial 表盘",
                              "Weather 天气",
                              "AlarmClock 闹钟",
                              "Camera 相机",
                              "Sedentary 久坐",
                              "Drink 喝水",
                              "Pressure 精神压力"]
    
    private var cmdArray:[[(String,MTKCmd)]] {
        get {
            var cmdAry:[[(String,MTKCmd)]] = []
            let ary = NSArray(contentsOfFile:Bundle.main.path(forResource: "KCTMTKTaskSendVC", ofType:"plist")!)!
            for i in 0..<ary.count {
                let section:NSArray = ary[i] as! NSArray
                var rowTmp:[(String,MTKCmd)] = []
                for row in section {
                    let dic = row as! [String : String]
                    let key = NSLocalizedString([String](dic.keys)[0], comment:"")
                    let value = MTKCmd(rawValue: [String](dic.values)[0])!
                    rowTmp.append((key,value))
                }
                cmdAry.append(rowTmp)
            }
            return cmdAry
        }
    }
    
    private let manager = KCTMTKShellManager.share
    
    @IBOutlet weak var reqTextView: UITextView!
    @IBOutlet weak var rspTextView: UITextView!
    
    
    //MARK: - View Life Cycle -
    override func viewDidLoad() {
        super.viewDidLoad()
        manager.setDelegate()
        manager.delegate = self
    }

    
    //MARK: - Clicks -
    @IBAction func clickBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func clickDisconnect(_ sender: Any) {
        manager.cancelConnection()
    }
    
    
    //MARK: - Tableview -
    func numberOfSections(in tableView: UITableView) -> Int {
        return headerName.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let diaries:NSArray = cmdArray[section] as NSArray
        return diaries.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return headerName[section]
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "BLECmdCellID")
        if  cell == nil {
            cell = Bundle.main.loadNibNamed("BLECmdCell", owner: nil, options: nil)?.first as? BLECmdCell
        }
        
        let cmdCell = cell as! BLECmdCell
        cmdCell.titleLabel.text = cmdArray[indexPath.section][indexPath.row].0 + "\n" +
                                  cmdArray[indexPath.section][indexPath.row].1.rawValue
        return cmdCell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         tableView.deselectRow(at: indexPath, animated: false)
        
        reqTextView.text = nil
        rspTextView.text = nil

        let cmd = cmdArray[indexPath.section][indexPath.row].1
        
        switch cmd {
        //MARK: - SET 设置 杂项 -
        case .SET_10:  //设置用户信息 (SET,10)
            set10()
        case .SET_15:  //设置APP运行状态 (SET,15)
            set15()
        case .SET_20:  //设置发票 (SET,20)
            set20()
        case .SET_22:  //设置收款码 (SET,22)
            set22()
        case .SET_35:  //设置单位 (SET,35)
            set35()
        case .SET_44:  //设置语言 (SET,44)
            set44()
        case .SET_45:  //设置时间 (SET,45)
            set45()
        case .SET_46:  //设置手势功能 (SET,46)
            set46()
        case .SETNEW_3://设置生理周期 (SETNEW,3)
            SETNEW3()

            
        //MARK: - Device 设备 -
        case .SET_40:           //查找设备 (SET,40)
            set40()
        case .FindDeviceNative: //查找设备 (原生)
            FindDeviceNative()
        case .GET_0:            //获取设备信息 (GET,0)
            get0()
        case .GET_1:            //同步设备数据 (GET,1)
            get1()
        case .RET_1:            //回复设备同步设备数据 (RET,1)
            ret1()
            
            
        //MARK: - Step 步数 -
        case .GET_2:        //同步计步时间段数据 (GET,2)
            get2()
        case .GET_10:       //获取计步数据 (GET,10)
            get10()
        case .GET_11:       //获取记步增量数据 (GET,11)
            get11()
        case .RET_2:        //回复设备同步计步时间段数据 (RET,2)
            ret2()
        case .RET_SEND_11:  //回复设备计步时间段增量数据 (RET,SEND,11)
            retSend11()
            
            
        //MARK: - Sleep 睡眠 -
        case .GET_3:        //同步睡眠时间段数据 (GET,3)
            get3()
        case .GET_12:       //获取汇总睡眠 (GET,12)
            get12()
        case .GET_13:       //获取详细的睡眠数据 (GET,13)
            get13()
        case .RET_3:        //回复设备同步睡眠时间段数据 (RET,3)
            ret3()
        case .RET_GET_12:   //回复设备获取汇总的睡眠数据 (RET,GET,12)
            retGet12()
        case .RET_GET_13:   //回复设备获取详细的睡眠数据 (RET,GET,13)
            retGet13()
            
            
        //MARK: - Sport 运动 -
        case .GET_17:       //获取运动历史数据索引 (GET,17)
            get17()
        case .GET_18:       //获取运动历史数据 (GET,18)
            get18()
        case .RET_GET_18:   //回复设备获取运动历史数据 (RET,GET,18)
            retGet18()
        case .RET_GET_18_1: //回复设备获取运动历史数据1 (RET,GET,18,1)
            retGet18_1()
            
            
        //MARK: - HeartRate 心率 -
        case .SET_19:       //设置心率监测 (SET,19)
            set19()
        case .GET_14:       //获取心率历史数据 (GET,14)
            get14()
        case .RET_GET_14:   //回复设备获取心率历史数据 (RET,GET,14)
            retGet14()
            
            
        //MARK: - ECG 心电 -
        case .SET_16:       //设置是否在ECG心电界面 (SET,16)
            set16()
        case .SET_17:       //设置ECG心电配置数据 (SET,17)
            set17()
        case .SET_18_ECG:   //设置ECG心电状态 (SET,18)
            set18_ECG()
        case .GET_20_ECG:   //获取ECG心电历史数据 (GET,20)
            get20_ECG()
            
            
        //MARK: - BloodPressure 血压 -
        case .SET_47:       //设置血压校准 (SET,47)
            set47()
        case .GET_51:       //获取血压历史数据 (GET,51)
            get51()
        case .RET_GET_51:   //回复设备获取血压历史数据 (RET,GET,51)
            retGet51()
            
            
        //MARK: - BloodOxygen 血氧 -
        case .GET_52:       //获取血氧历史数据 (GET,52)
            get52()
        case .RET_GET_52:   //回复设备获取血氧历史数据 (RET,GET,52)
            retGet52()
            
            
        //MARK: - Dial 表盘 -
        case .GETNEW_1:     //获取表盘推送支持信息 (GETNEW,1,)
            GETNEW1()
        case .SETNEW_1:     //设置表盘参数 (SETNEW,1)
            SETNEW1()
        case .SETNEW_2:     //发送表盘数据 (SETNEW,2)
            SETNEW2()
            
            
        //MARK: - Weather 天气 -
        case .SET_18:       //设置气象指数 (SET,18)
            set18()
        case .SET_Weather:  //设置天气 (WEATHER)
            setWeather()
        case .SETNEW_4:     //设置天气1 (SETNEW,4)
            setWeather1()
        case .GETNEW_3:     //设置逐小时天气 (GETNEW,3,) 7天 7小时
            setWeatherHour()

            
        //MARK: - AlarmClock 闹钟 -
        case .SET_13:       //设置闹钟 (SET,13)
            set13()
        case .GET_15:       //获取闹钟数据 (GET,15)
            get15()
        case .RET_GET_15:   //回复设备获取闹钟数据 (RET,GET,15)
            retGet15()
            

        //MARK: - Camera 相机 -
        case .SET_14:       //设置相机开关状态 (SET,14) (部分设备支持该功能)
            set14()
        case .RET_SET_14:   //回复设备设置相机开关状态 (RET,SET,14)
            retSet14()
    
            
        //MARK: - Sedentary 久坐 -
        case .SET_12:       //设置久坐提醒 (SET,12)
            set12()
        case .RET_SET_12_1: //回复设备设置久坐提醒 (RET,SET,12,1)
            retSet12_1()
            
            
        //MARK: - Drink 喝水 -
        case .SET_21:       //设置喝水提醒 (SET,21)
            set21()
        case .RET_SET_21_1: //回复设备设置喝水提醒 (RET,SET,21,1)
            retSet21_1()
            
        //MARK: - Pressure 精神压力 -
        case .GETNEW_2://获取精神压力 (GETNEW,2)
            GETNEW2()
        case .RET_GETNEW_2://获取精神压力 (GETNEW,2)
            retGETNEW2()
            
        case .UNKNOW:
            return
        }
    }

     
    //MARK: - SET 设置 杂项 -
    //MARK: SET_10 设置用户信息 (SET,10)
    func set10() {
        let phs = ["目标步数",//范围4000~20000，以500一个阶梯变化
                   "性别(0-女，1-男)",
                   "身高(cm)",//位cm，范围50~229
                   "体重(kg)"]//单位kg，范围30~229
        self.showMultiTextInput(title: "设置用户信息",
                                message: nil,
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            if let goal = Int(contents[0]),
               let sex = Int(contents[1]) ,
               let h = Int(contents[2])   ,
               let w = Int(contents[3])   {
               let s = sex != 0 ? 1 : 0
               let task = KCTMTKTaskSetUserInfos.init(goal: goal,
                                                      sex: s,
                                                      height: h,
                                                      weight: w,
                                                      completion: {[weak self] (tsk, result, error) in
                self?.rspTextView.text = ResultContent(title: "SET,10",
                                                       error: error,
                                                       rspDes: "\(result)")
            })
                self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: SET_15 设置APP运行状态 (SET,15)
    func set15() {
        self.showTextInput(title: "设置APP运行状态 (SET,15)",
                           message: "0-后台，1-前台") { (text) in
            if let tag = Int(text){
               let foreground = tag != 0
               let task = KCTMTKTaskSetPhoneState.init(runForeground: foreground,
                                                       completion: {[weak self] (error) in
                    self?.rspTextView.text = ResultContent(title: "设置APP运行状态 (SET,15)",
                                                           error: error,
                                                           rspDes: nil)
                })
                self.manager.resume(mtkTask: task)
                self.reqTextView.text = ReqContent(title: "设置APP运行状态 (SET,15)",
                                                 content: "\(foreground)")
            }else{
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: SET_20 设置发票 (SET,20)
    func set20() {
        self.showTextInput(title: "设置电子发票",
                           message: "填写发票数量") {[weak self] (text) in
            if let count = Int(text), count >= 0{
                var array = Array<MTKInvoice>.init()
                for i in 0 ..< count {
                    let invoice = MTKInvoice.init()
                    invoice.name = "抬头\(i)"
                    invoice.TFN = "TFN\(i)"
                    invoice.address = "地址\(i)"
                    invoice.phoneNum = "电话\(i)"
                    invoice.bankName = "银行\(i)"
                    invoice.bankAccount = "帐号\(i)"
                    invoice.remarks = "备注\(i)"
                    invoice.userId = 10000 + i
                    invoice.invoiceId = 20000 + i
                    invoice.defaultId = 30000 + i
                    array.append(invoice)
                }
                
                let task = KCTMTKTaskSetInvoices.init(invoinces: array, completion: {[weak self] (tsk, result, error) in
                    self?.rspTextView.text = ResultContent(title: "设置电子发票",
                                                           error: error,
                                                           rspDes: "\(result)")
                })
                
                let tempArray = NSArray.init(array: array)
                self?.manager.resume(mtkTask: task)
                self?.reqTextView.text = ReqContent(title: "设置发票 (SET,20)",
                                                    content: "\(tempArray.yy_modelToJSONObject() ?? "空")")
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: SET_22 设置收款码 (SET,22)
    func set22() {
        let phs = ["平台。0-支付宝，1-微信",
                   "二维码字符串。内容为空，则表示清除二维码"]
        self.showMultiTextInput(title: "设置收款码",
                                message: nil,
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            if let p = Int(contents[0]) {
                let qrStr = contents[1].count > 0 ? contents[1] : nil
                let task = KCTMTKTaskSetCollectionQR.init(platform: p, QRString: qrStr, completion: { (tsk, result, error) in
                    self?.rspTextView.text = ResultContent(title: "设置收款码 (SET,22)",
                                                           error: error,
                                                           rspDes: "\(result)")
                })
                self?.manager.resume(mtkTask: task)
                self?.reqTextView.text = ReqContent(title: "设置收款码 (SET,22)",
                                                    content: "\(task.yy_modelToJSONObject() ?? "空")")
            }
        }
    }
    
    //MARK: SET_35 设置单位 (SET,35)
    func set35() {
        let phs = ["0-公制，1-英制","0-摄氏度，1-华氏度"]
        self.showMultiTextInput(title: "单位设置",
                                message: nil,
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            if let measure = Int(contents[0]),
               let temp = Int(contents[1]) {
               let task = KCTMTKTaskSetUnitSystem.init(measureType: measure,
                                                       temperatureType: temp,
                                                       completion: {[weak self] (tsk, result, error) in
                    self?.rspTextView.text = ResultContent(title: "设置单位 (SET,35)",
                                                           error: error,
                                                           rspDes: result.description)
                })
                self?.manager.resume(mtkTask: task)
                self?.reqTextView.text = ReqContent(title: "设置单位 (SET,35)",
                                                    content: "\(measure), \(temp)")
            } else {
                SVProgressHUD.showInfo(withStatus: "输入有误")
            }
        }
    }
    
    //MARK: SET_44 设置语言 (SET,44)
    func set44() {//英语:en_US 繁体中文:zh_TW 简体中文:zh_CN
        self.showTextInput(title: "设置语言",
                           message: nil) {[weak self] (text) in
            let task = KCTMTKTaskSetLanguage.init(language: text)
            self?.manager.resume(mtkTask: task)
            self?.reqTextView.text = "设置语言 (SET,44) \(text)"
        }
    }
    
    //MARK: SET_45 设置时间 (SET,45)
    func set45() {
        let phs = ["0-12小时制，1-24小时制",
                   "时区。eg 8:东8区，-6:西6区",
                   "时间戳。秒"]
        let zone = TimeZone.current.secondsFromGMT()/60/60
        let ts = Int(Date.init().timeIntervalSince1970)
        let cs = ["0",
                  "\(zone)",
                  "\(ts)"]
        self.showMultiTextInput(title: "设置时间",
                                message: nil,
                                lines: phs.count,
                                placeHolders: phs,
                                contents: cs) {[weak self] (contents) in
            if let type = Int(contents[0]),
               let zone = Int(contents[1]),
               let ts   = Int(contents[2]){
               let task = KCTMTKTaskSetTime.init(use24Format: type != 0,
                                                 zone: zone,
                                                timestamp: ts)
               self?.manager.resume(mtkTask: task)
               self?.rspTextView.text = "设置时间 (SET,45)"
            } else {
                SVProgressHUD.showInfo(withStatus: "输入有误")
            }
        }
    }
    
    //MARK: SET_46 设置手势功能 (SET,46)
    func set46() {
        let task = KCTMTKTaskSetGestureFunction.init(raiseSreenOn: true,
                                                     flipHangUpPhone: false,
                                                     mutAlarm: true,
                                                     shakePaging: true,
                                                     shakeAnswer: true) {[weak self] (tsk, result, error) in
            self?.rspTextView.text = ResultContent(title: "SET,46",
                                                   error: error,
                                                   rspDes: "\(result)")
        }
//        let task = KCTMTKTaskSetGestureFunction.init(raiseSreenOn: true, flipHangUpPhone: true, mutAlarm: true, shakePaging: true, shakeAnswer: true, completion: nil)
//        manager.timeout = 0 // 设备无响应引起超时，实际设置成功，可以忽略超时
        manager.resume(mtkTask: task)
    }
    
    //MARK: SETNEW_3 设置生理周期 (SETNEW,3)
    func SETNEW3() {
        let task = KCTMTKTaskSetMenstrual.init(date:     "",
                                               continued: 1,
                                               cycle:     0,
                                               length:   10,
                                               remind:    1,
                                               moment:    0,
                                               completion: {[weak self] (tsk, result, error) in
            self?.rspTextView.text = ResultContent(title: "SETNEW_3",
                                                   error: error,
                                                   rspDes: result?.yy_modelToJSONString())
        })
        manager.resume(mtkTask: task)
    }
    
    
    //MARK: - GET 获取 杂项 -

    
    //MARK: - Device 设备 -
    //MARK: SET_40 查找设备 (SET,40)
    func set40() {
        let task = KCTMTKTaskFindDevice.init(onoff: true) {[weak self] (error) in
            self?.rspTextView.text = ResultContent(title: "查找设备 (SET,40)",
                                                   error: error,
                                                   rspDes: nil)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: Native 查找设备 (原生)
    func FindDeviceNative() {
        let task = KCTMTKTaskFindDeviceNativeProtocol.init()
        manager.resume(mtkTask: task)
        reqTextView.text = "查找设备 (原生)"
    }

     
    //MARK: GET_0 获取设备信息 (GET,0)
    func get0() {
        let task = KCTMTKTaskGetDevInfo.init {[weak self] (tsk, checkModel, error) in
            let des = "\(checkModel?.yy_modelToJSONObject() ?? "空")"
            self?.rspTextView.text = ResultContent(title: "获取设备信息 (GET,0)",
                                                   error: error,
                                                   rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: GET_1 同步设备数据 (GET,1)
    func get1() {
        let task = KCTMTKTaskSyncDevData.init(completion: {[weak self] (tsk, result, error) in
            let array = NSMutableArray.init()
            for model in result ?? [] {
                array.add(model)
            }
            let des = "\(array.yy_modelToJSONObject() ?? "空")"
            self?.rspTextView.text = ResultContent(title: "同步设备数据 (GET,1)",
                                                   error: error,
                                                   rspDes: des)
        })
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_1 回复设备同步设备数据 (RET,1)
    func ret1() {
        let task = KCTMTKTaskRspSyncDevData.init(success: true)
        manager.resume(mtkTask: task)
        rspTextView.text = "回复设备同步设备数据 (RET,1)"
    }
    
    
    //MARK: - Step 步数 -
    //MARK: GET_2 同步计步时间段数据 (GET,2)
    func get2() {
        let task = KCTMTKTaskSyncStepPeriodData.init(completion: {[weak self] (tsk, result, error) in
            let array = NSMutableArray.init()
            for model in result ?? [] {
                array.add(model)
            }
            let des = "\(array.yy_modelToJSONObject() ?? "空")"
            self?.rspTextView.text = ResultContent(title: "同步计步时间段数据 (GET,2)",
                                                   error: error,
                                                   rspDes: des)
        })
        manager.resume(mtkTask: task)
    }
    
    //MARK: GET_10 获取计步数据 (GET,10)
    func get10() {
        let task = KCTMTKTaskGetDailyStep.init {[weak self] (tsk, models, error) in
            let array = NSMutableArray.init()
            for model in models ?? [] {
                array.add(model)
            }
            let des = "\(array.yy_modelToJSONObject() ?? "空")"
            self?.rspTextView.text = ResultContent(title: "GET,10", error: error, rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: GET_11 获取记步增量数据 (GET,11)
    func get11() {
        let task = KCTMTKTaskGetDeltaStep.init {[weak self] (tsk, list, error) in
            let des = "\(list?.yy_modelToJSONObject() ?? "空")"
            self?.rspTextView.text = ResultContent(title: "获取记步增量数据 (GET,11)",
                                                   error: error,
                                                   rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_2 回复设备同步计步时间段数据 (RET,2)
    func ret2() {
        let task = KCTMTKTaskRspSyncStepPeriodData.init(success: true)
        manager.resume(mtkTask: task)
        reqTextView.text = "回复设备同步计步时间段数据 (RET,2)"
    }
    
    //MARK: RET_SEND_11 回复设备计步时间段增量数据 (RET,SEND,11)
    func retSend11() {
        let task = KCTMTKTaskRspStepPeriodDeltaData.init(success: true)
        manager.resume(mtkTask: task)
        rspTextView.text = "回复设备计步时间段增量数据 (RET,SEND,11)"
    }
    
    
    //MARK: - Sleep 睡眠 -
    //MARK: GET_3 同步睡眠时间段数据 (GET,3)
    func get3() {
        let task = KCTMTKTaskSyncSleepPeriodData.init(completion: {[weak self] (tsk, result, error) in
            var des = ""
            if let ary = result {
                let array = NSArray.init(array: ary)
                des = "\(array.yy_modelToJSONObject() ?? "空")"
            }
            self?.rspTextView.text = ResultContent(title: "GET_3",
                                                   error: error,
                                                   rspDes: des)
        })
        manager.resume(mtkTask: task)
    }
    
    //MARK: GET_12 获取汇总睡眠 (GET,12)
    func get12() {
        let task = KCTMTKTaskGetSummarizedSleep.init {[weak self] (tsk, sleeps, error) in
            var des = ""
            if let ary = sleeps {
               let array = NSArray.init(array: ary)
               des = "\(array.yy_modelToJSONObject() ?? "空")"
            }
            self?.rspTextView.text = ResultContent(title: "GET,12",
                                                   error: error,
                                                   rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: GET_13 获取详细的睡眠数据 (GET,13)
    func get13() {
        let task = KCTMTKTaskGetDetailSleep.init {[weak self] (tsk, sleeps, error) in
            var des = ""
            if let ary = sleeps {
                let array = NSArray.init(array: ary)
                des = "\(array.yy_modelToJSONObject() ?? "空")"
            }
            self?.rspTextView.text = ResultContent(title: "GET,13",
                                                   error: error,
                                                   rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_3 回复设备同步睡眠时间段数据 (RET,3)
    func ret3() {
        let task = KCTMTKTaskRspSyncSleepPeriodData.init(success: true)
        manager.resume(mtkTask: task)
        rspTextView.text = "回复设备同步睡眠时间段数据 (RET,3)"
    }
    
    //MARK: RET_GET_12 回复设备获取汇总的睡眠数据 (RET,GET,12)
    func retGet12() {
        let task = KCTMTKTaskRspGetSummarizedSleep.init(success: true)
        manager.resume(mtkTask: task)
        rspTextView.text = "回复设备获取汇总的睡眠数据 (RET,GET,12)"
    }
    
    //MARK: RET_GET_13 回复设备获取详细的睡眠数据 (RET,GET,13)
    func retGet13() {
        let task = KCTMTKTaskRspGetDetailSleep.init(success: true)
        manager.resume(mtkTask: task)
        rspTextView.text = "回复设备获取详细的睡眠数据 (RET,GET,13)"
    }
    
    
    //MARK: - Sport 运动 -
    //MARK: GET_17 获取运动历史数据索引 (GET,17)
    func get17() {
        let task = KCTMTKTaskGetSportIndexs.init {[weak self] (tsk, indexes, error) in
            var content = ""
            if let ids = indexes {
               content = NSArray.init(array: ids).componentsJoined(by: ",")
            }
            self?.rspTextView.text = ResultContent(title: "获取运动历史数据索引 (GET,17)", error: error, rspDes: content)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: GET_18 获取运动历史数据 (GET,18)
    func get18() {
        self.showTextInput(title: "获取运动历史数据 (GET,18)", message: nil) {[weak self] (text) in
            if  let index = Int(text) {
                let task = KCTMTKTaskGetSport.init(index: index,
                                                   completion: {[weak self] (tsk, result, error) in
                                                    self?.rspTextView.text = ResultContent(title: "获取运动历史数据 (GET,18)", error: error, rspDes: result?.yy_modelToJSONString())
                })
                self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showError(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: RET_GET_18 回复设备获取运动历史数据 (RET,GET,18)
    func retGet18() {
        let task = KCTMTKTaskRspGetSport.init(index: 1)
        self.manager.resume(mtkTask: task)
        reqTextView.text = "回复设备获取运动历史数据 (RET,GET,18)"
    }
    
    //MARK: RET_GET_18_1 回复设备获取运动历史数据1 (RET,GET,18,1)
    func retGet18_1() {
        let task = KCTMTKTaskRspGetSport1.init(index: 1, total: 1)
        self.manager.resume(mtkTask: task)
        reqTextView.text = "回复设备获取运动历史数据1 (RET,GET,18)"
    }
    
    
    //MARK: - HeartRate 心率 -
    //MARK: GET_14 获取心率历史数据 (GET,14)
    func get14() {
        let task = KCTMTKTaskGetHeartRate.init {[weak self] (tsk, hrs, error) in
            var des = ""
            if let ary = hrs {
               let array = NSArray.init(array: ary)
               des = "\(array.yy_modelToJSONObject() ?? "空")"
            }
            self?.rspTextView.text = ResultContent(title: "获取心率历史数据 (GET,14)", error: error, rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_GET_14 回复设备获取心率历史数据 (RET,GET,14)
    func retGet14() {
        let task = KCTMTKTaskRspGetHeartRate.init(success: true)
        manager.resume(mtkTask: task)
        reqTextView.text = "回复设备获取心率历史数据 (RET,GET,14)"
    }
 
    //MARK: SET_19 设置心率监测 (SET,19)
    func set19() {
        let phs = ["0-关闭，1-开启",
                   "开始时间。HH:mm",
                   "结束时间。HH:mm",
                   "监测间隔(分)"]
        self.showMultiTextInput(title: "设置心率监测 (SET,19)",
                                message: nil,
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            let startCmps = contents[1].components(separatedBy: ":")
            let endCmps   = contents[2].components(separatedBy: ":")
            if startCmps.count > 1,
               endCmps.count   > 1,
               
               let openTag = Int(contents[0]),
               let startH = Int(startCmps[0]),
               let startM = Int(startCmps[1]),
               let endH = Int(endCmps[0]),
               let endM = Int(endCmps[1]),
               let interval = Int(contents[3] ){
                
               let task = KCTMTKTaskSetHeartRateCheck.init(open: openTag != 0,
                                                           startH: startH,
                                                           startM: startM,
                                                           endH: endH,
                                                           endM: endM,
                                                           interval: interval,
                                                           completion: {[weak self] (tsk, result, error) in
                    self?.rspTextView.text = ResultContent(title: "设置心率监测 (SET,19)", error: error, rspDes: nil)
                })
                self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    
    //MARK: - ECG 心电 -
    //MARK: SET_16 设置是否在ECG心电界面 (SET,16)
    func set16() {
        let task = KCTMTKTaskSetECGView.init(bEcgView: 1)
        manager.resume(mtkTask: task)
        reqTextView.text = "设置是否在ECG心电界面 (SET,16)"
    }

    //MARK: SET_17 设置ECG心电配置数据 (SET,17)
    func set17() {
        let task = KCTMTKTaskSetECGConfig.init(speed: 10, gain: 25, rate: 24, dimension: 350)
        manager.resume(mtkTask: task)
        reqTextView.text = "设置ECG心电配置数据 (SET,17)"
    }
    
    //MARK: SET_18 设置ECG心电状态 (SET,18)
    func set18_ECG() {
        let task = KCTMTKTaskSetECGStatus.init(bStart: 1)
        manager.resume(mtkTask: task)
        reqTextView.text = "设置ECG心电状态 (SET,18)"
    }
    
    //MARK: GET_20 获取ECG心电历史数据 (GET,20)
    func get20_ECG() {
        let task = KCTMTKTaskGetECGHistory.init(completion: {[weak self] (tsk, result, error) in
            self?.rspTextView.text = ResultContent(title: "获取ECG心电历史数据 (GET,20)", error: error, rspDes: "\(String(describing: result))")
        })
        manager.resume(mtkTask: task)
    }
    
    
    //MARK: - BloodPressure 血压 -
    //MARK: SET_47 设置血压校准 (SET,47)
    func set47() {
        let task = KCTMTKTaskSetBloodPressureCorrect.init(systolic: 50,
                                                          diastolic: 100,
                                                          on: true)
        manager.resume(mtkTask: task)
        reqTextView.text = "设置血压校准 (SET,47)"
    }
    
    //MARK: GET_51 获取血压历史数据 (GET,51)
    func get51() {
        let task = KCTMTKTaskGetBloodPressure.init {[weak self] (tsk, bps, error) in
            var des = ""
            if let ary = bps {
               let array = NSArray.init(array: ary)
               des = "\(array.yy_modelToJSONObject() ?? "空")"
            }
            self?.rspTextView.text = ResultContent(title: "获取血压历史数据 (GET,51)", error: error, rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_GET_51 回复设备获取血压历史数据 (RET,GET,51)
    func retGet51() {
        let task = KCTMTKTaskRspGetBloodPressure.init()
        manager.resume(mtkTask: task)
        reqTextView.text = "回复设备获取血压历史数据 (RET,GET,51)"
    }
    
    
    //MARK: - BloodOxygen 血氧 -
    //MARK: GET_52 获取血氧历史数据 (GET,52)
    func get52() {
        let task = KCTMTKTaskGetBloodOxygen.init {[weak self] (tsk, bos, error) in
            var des = ""
            if let ary = bos {
               let array = NSArray.init(array: ary)
               des = "\(array.yy_modelToJSONObject() ?? "空")"
            }
            self?.rspTextView.text = ResultContent(title: "获取血氧历史数据 (GET,52)", error: error, rspDes: des)
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_GET_52 回复设备获取血氧历史数据 (RET,GET,52)
    func retGet52() {
        let task = KCTMTKTaskRspGetBloodOxygen.init()
        manager.resume(mtkTask: task)
        reqTextView.text = "回复设备获取血氧历史数据 (RET,GET,52)"
    }
    
    
    //MARK: - Dial 表盘 -
    //MARK: GETNEW_1 获取表盘推送支持信息 (GETNEW,1,)
    func GETNEW1() {
        let task = KCTMTKTaskGetDialSupportInfo.init(completion: {[weak self] (tsk, result, error) in
            self?.rspTextView.text = ResultContent(title: "获取表盘推送支持信息 (GETNEW,1,)",
                                                   error: error,
                                                   rspDes: result?.yy_modelToJSONString())
        })
        manager.resume(mtkTask: task)
    }
    
    //MARK: SETNEW_1 设置表盘参数 (SETNEW,1)
    func SETNEW1() {
        let task = KCTMTKTaskSetDialParams.init(size: 66,
                                                completion: {[weak self] (tsk, infos, error) in
            self?.rspTextView.text = ResultContent(title: "设置表盘参数 (SETNEW,1)",
                                                   error: error,
                                                   rspDes: infos?.yy_modelToJSONString())
        })
        manager.resume(mtkTask: task)
    }
    
    //MARK: SETNEW_2 发送表盘数据 (SETNEW,2)
    func SETNEW2() {
        let dataT = NSData.init()
        let task = KCTMTKTaskSendDial.init(packetSum: 10,
                                           packetIndex: 1,
                                           data: dataT as Data,
                                           completion: {[weak self] (tsk, result, error) in
            self?.rspTextView.text = ResultContent(title: "发送表盘数据 (SETNEW,2)",
                                                   error: error,
                                                   rspDes: result?.yy_modelToJSONString())
        })
        manager.resume(mtkTask: task)
    }
    
    
    //MARK: - Weather 天气 -
    //MARK: SET_18 设置气象指数 (SET,18)
    func set18() {
        let task =  KCTMTKTaskSetWeatherIndex.init(pressure: 1,
                                                   altitude: 1,
                                                   UV: 1,
                                                   temperature: 1,
                                                   sunRiseTime: "09:00",
                                                   sunSetTime: "19:09",
                                                   RH: 1,
                                                   completion: nil)
        self.manager.resume(mtkTask: task)
        reqTextView.text = "设置气象指数 (SET,18)"
    }
    
    //MARK: SET_Weather 设置天气 (WEATHER)
    func setWeather() {
        let phs = ["测试天气数据的个数", "城市名称。eg. shenzhen"]
        self.showMultiTextInput(title: "设置天气 (WEATHER)",
                                message: "推送从今天开始若干天的天气(测试数据)",
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            if  let count = Int(contents[0]) {
                let cal    = Calendar.current
                let nowTS  = Date.init().timeIntervalSince1970
                let format = DateFormatter.init()
                format.dateFormat = "yyyy-MM-dd"
                
                var ary = Array<MTKPushWeather>.init()
                for i in 0 ..< count {
                    let ts = nowTS + 60.0 * 60.0 * 24.0 * Double(i)
                    let date = Date.init(timeIntervalSince1970: ts)
                    let weather = MTKPushWeather.init()
                    weather.highTemperature = 99
                    weather.lowTemperature  = 66
                    weather.weatherCode     = 4
                    weather.week       = cal.component(.weekday, from: date)
                    weather.dateString = format.string(from: date)
                    ary.append(weather)
                }
                
                let task = KCTMTKTaskSetWeather.init(city: contents[1], weathers: ary, completion: nil)
//                let task = KCTMTKTaskSetWeather.init(city:contents[1],
//                                                     weathers:ary) {[weak self] (tsk, result, error) in
//                    self?.rspTextView.text = ResultContent(title: "设置天气 (WEATHER)",
//                                                           error: error,
//                                                           rspDes: nil)
//                }
                self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }

    //MARK: SET_Weather1 设置天气1 (SETNEW,4)
    func setWeather1() {
        let phs = ["测试天气数据的个数","城市名称。eg. shenzhen"]
        self.showMultiTextInput(title: "设置天气1 (SETNEW,4)",
                                message: "推送从今天开始若干天的天气(测试数据)",
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            if  let count = Int(contents[0]){
                let cal = Calendar.current
                let nowTS = Date.init().timeIntervalSince1970
                let format = DateFormatter.init()
                format.dateFormat = "yyyy-MM-dd"
                
                var ary = Array<MTKPushWeather>.init()
                for i in 0 ..< count {
                    let ts = nowTS + 60.0 * 60.0 * 24.0 * Double(i)
                    let date = Date.init(timeIntervalSince1970: ts)
                    let weather = MTKPushWeather.init()
                    weather.highTemperature = 88
                    weather.lowTemperature  = 77
                    weather.weatherCode     = 5
                    weather.week       = cal.component(.weekday, from: date)
                    weather.dateString = format.string(from: date)
                    ary.append(weather)
                }
                
                let task = KCTMTKTaskSetWeather1.init(temperature: 88, weathers: ary, completion: nil)
//                let task = KCTMTKTaskSetWeather1.init(temperature:88,
//                                                         weathers:ary) {[weak self] (tsk, result, error) in
//                    self?.rspTextView.text = ResultContent(title: "设置天气1 (SETNEW,4)",
//                                                           error: error,
//                                                           rspDes: nil)
//                }
                self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: SET_WeatherHour 设置逐小时天气 (GETNEW,3,) 7天 7小时
    func setWeatherHour() {
        var weathers = Array<MTKPushWeather1>.init()
        for _ in 0 ..< 7 {
            let weather = MTKPushWeather1.init()
            weather.highTemperature = 99
            weather.lowTemperature  = 66
            weather.weatherCode     = 3
            weathers.append(weather)
        }
        
        var hours = Array<MTKPushWeatherHour>.init()
        for _ in 0 ..< 7 {
            let hour = MTKPushWeatherHour.init()
            hour.temperature = 99
            hour.weatherCode = 3
            hours.append(hour)
        }
        let task = KCTMTKTaskSetWeatherHour.init(weathers: weathers, weatherHours: hours)
        manager.resume(mtkTask: task)
    }
    
    
    //MARK: - AlarmClock 闹钟 -
    //MARK: SET_13 设置闹钟 (SET,13)
    func set13() {
        let ac = MTKAlarmClock.init();
        ac.time = "14:14"  // 闹钟时间，保持两位数来描述，如08：00
        ac.days = "0111111"// 周日，周一~周六，0表示不使用，1为开启，如果全部为0，表示闹钟响一次
        ac.ring = 3        // 闹钟铃声
        ac.alertType = 2   // 提示类型，0：仅响铃，1：仅震动，2：震动及响铃
        ac.flag = 1        // 闹钟是否开启使用，0：表示不开启，1表示开启
        ac.type = 5        // 提醒类型 0：吃饭（EAT），1：吃药（MEDCINE），2：会议（MEETING），3：睡眠（SLEEP），4：运动（SPORT），5：起床（WAKEUP
        let task = KCTMTKTaskSetAlarmClock.init(acs: [ac],
                                                completion: {[weak self] (tsk, result, error) in
            self?.rspTextView.text = ResultContent(title: "设置闹钟 (SET,13)",
                                                   error: error,
                                                   rspDes: "\(result)")
        })
        manager.resume(mtkTask: task)
    }
    
    //MARK: GET_15 获取闹钟数据 (GET,15)
    func get15() {
        let task = KCTMTKTaskGetAlarmClock.init(completion: {[weak self] (tsk, result, error) in
            let array = NSMutableArray.init()
            for model in result ?? [] {
                array.add(model)
            }
            let des = "\(array.yy_modelToJSONObject() ?? "空")"
            self?.rspTextView.text = ResultContent(title: "获取闹钟数据 (GET,15)",
                                                   error: error,
                                                   rspDes: des)
        })
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_GET_15 回复设备获取闹钟数据 (RET,GET,15)
    func retGet15() {
        let task = KCTMTKTaskRspGetAlarmClock.init(success: true)
        manager.resume(mtkTask: task)
        reqTextView.text = "回复设备获取闹钟数据 (RET,GET,15)"
    }
    
    
    //MARK: - Camera 相机 -
    //MARK: SET_14 设置相机开关状态 (SET,14) (部分设备支持该功能)
    func set14() {
        self.showTextInput(title: "设置相机开关状态 (SET,14)",
                           message: "0-已关闭,1-已开启") {[weak self] (text) in
            if let tag = Int(text) {
               let task = KCTMTKTaskSetCamera.init(cameraIsOn: tag != 0,
                                                   completion: {[weak self] (tsk, result, error) in
                    self?.rspTextView.text = ResultContent(title: "设置相机开关状态 (SET,14)",
                                                           error: error,
                                                           rspDes: "\(result)")
                })
                self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: RET_SET_14 回复设备设置相机开关状态 (RET,SET,14)
    func retSet14() {
        let task = KCTMTKTaskRspCameraStatus.init(success: true)
        manager.resume(mtkTask: task)
        rspTextView.text = "RET_SET_14 回复设备设置相机开关状态 (RET,SET,14)"
    }
    
    
    //MARK: - Sedentary 久坐 -
    //MARK: SET_12 设置久坐提醒 (SET,12)
    func set12() {
        let phs = ["间隔(分)",
                   "0-关闭，1-开启",
                   "开始时间。 HH:mm",
                   "结束时间。HH:mm",
                   ]
        self.showMultiTextInput(title: "设置久坐提醒 (SET,12)",
                                message: nil,
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            if let interval = Int(contents[0]),
               let openTag = Int(contents[1]) {
               let start = contents[2]
               let end = contents[3]
               let task = KCTMTKTaskSetSedentaryReminder.init(time: interval,
                                                              on: openTag,
                                                              start: start,
                                                              end: end,
                                                              completion: {[weak self] (tsk, result, error) in
                    self?.rspTextView.text = ResultContent(title: "设置久坐提醒 (SET,12)",
                                                           error: error,
                                                           rspDes: "\(result)")
                })
                self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: RET_SET_12_1 回复设备设置久坐提醒 (RET,SET,12,1)
    func retSet12_1() {
        let task = KCTMTKTaskRspSetSedentaryReminder.init(success: true)
        manager.resume(mtkTask: task)
        reqTextView.text = "回复设备设置久坐提醒 (RET,SET,12,1)"
    }

    
    //MARK: - Drink 喝水 -
    //MARK: SET_21 设置喝水提醒 (SET,21)
    func set21() {
        let phs = ["间隔(分)",
                   "0-关闭，1-开启",
                   "开始时间。 HH:mm",
                   "结束时间。HH:mm",
                   ]
        self.showMultiTextInput(title: "设置喝水提醒",
                                message: nil,
                                lines: phs.count,
                                placeHolders: phs) {[weak self] (contents) in
            if let interval = Int(contents[0]),
               let openTag = Int(contents[1]) {
               let start = contents[2]
               let end = contents[3]
               let task = KCTMTKTaskSetDrinkReminder.init(time: interval,
                                                          on: openTag,
                                                          start: start,
                                                          end: end,
                                                          completion: {[weak self] (tsk, result, error) in
                    self?.rspTextView.text = ResultContent(title: "设置喝水提醒 (SET,21)",
                                                           error: error,
                                                           rspDes: "\(result)")
               })
               self?.manager.resume(mtkTask: task)
            } else {
                SVProgressHUD.showInfo(withStatus: "输入错误")
            }
        }
    }
    
    //MARK: RET_SET_21_1 回复设备设置喝水提醒 (RET,SET,21,1)
    func retSet21_1() {
        let task = KCTMTKTaskRspSetDrinkReminder.init(success: true)
        manager.resume(mtkTask: task)
        rspTextView.text = "回复设备设置喝水提醒 (RET,SET,21,1)"
    }
    
    
    //MARK: - Pressure 精神压力 -
    //MARK: GETNEW_2 获取精神压力 (GETNEW,2)
    func GETNEW2() {
        let task = KCTMTKTaskGetPressure.init {[weak self] (tsk, pressures, error) in
            self?.rspTextView.text = ResultContent(title: "GETNEW_2",
                                                   error: error,
                                                   rspDes: pressures?.yy_modelToJSONString())
        }
        manager.resume(mtkTask: task)
    }
    
    //MARK: RET_GETNEW_2 回复设备获取精神压力 (RET,GETNEW,2,)
    func retGETNEW2() {
        let task = KCTMTKTaskRspGetPressure.init()
        manager.resume(mtkTask: task)
        reqTextView.text = "回复设备获取精神压力 (RET,GETNEW,2,)"
    }
    
    
    //MARK: - Delagate 回调 -    
    /// 连接成功回调（调用连接方法后，握手成功才真正连接成功）
    func mtkShellManagerShakedHands(manager: KCTMTKShellManager) {
        rspTextView.text = "✅ \(NSLocalizedString("连接成功", comment: "")) 🤝"
    }
    
    /// 连接失败回调（调用连接方法后，握手成功才真正连接成功）
    func mtkShellManagerFailedToConnect(manager:KCTMTKShellManager, error:KCTError) {
        rspTextView.text = "❌ \(NSLocalizedString("连接错误", comment: "")) error:  \(error.errInfo)"
    }
    
    func mtkShellManager(manager: KCTMTKShellManager, received cmd: String, activeMessage: Any?) {
        rspTextView.text = "\(NSLocalizedString("接收到设备发送的数据", comment: "")):\n cmd:\(cmd)\n message: \n\(activeMessage.debugDescription )"
    }
}
